package cn.aixuxi.security.controller;

import cn.aixuxi.security.entity.SysRole;
import cn.aixuxi.security.entity.SysUser;
import cn.aixuxi.security.entity.SysUserRole;
import cn.aixuxi.security.service.SysRoleService;
import cn.aixuxi.security.service.SysUserRoleService;
import cn.aixuxi.security.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * 类描述 用户相关
 *
 * @author ruozhuliufeng
 * @version 1.0
 * @date 2021/4/22 22:20
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @GetMapping("index")
    public String index(Model model){
        List<SysUser> userList = sysUserService.list();
        model.addAttribute("userList",userList);
        List<SysRole> roleList = roleService.list();
        model.addAttribute("roleList",roleList);
        return "user";
    }

    @PostMapping("add")
    public String add(SysUser user){
        // 对密码进行加密处理
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        sysUserService.save(user);
        // 刷新页面
        return "redirect:/user/index";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable("id") Integer id, Model model){
        SysUser user = sysUserService.getById(id);
        model.addAttribute("updateUser",user);
        return "user_update";
    }

    @PostMapping("update")
    public String update(SysUser user){
        sysUserService.save(user);
        // 刷新页面
        return "redirect:/user/index";
    }
    @GetMapping("delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        sysUserService.removeById(id);
        // 刷新页面
        return "redirect:/user/index";
    }

    @PostMapping("addRole")
    public String addRole(SysUserRole userRole){
        userRoleService.saveOrUpdate(userRole);
        return "redirect:/user/index";
    }
}
